<?php

namespace yak\layui\widgets\form;

use yii\helpers\Html;
use yii\web\View;
use yii\widgets\InputWidget;

/**
 * Class CheckBoxList
 * @package yak\layui\widgets\form
 */
class CheckBoxList extends InputWidget
{
    /**
     * @var array
     */
    public $items = [];

    public function run()
    {
        $id = $this->getId();
        $filter = $id . '-filter';
        $value = (string)$this->model[$this->attribute];
        $options = ['unselect' => $value];
        $options['item'] = function ($index, $label, $name, $checked, $value) use($filter) {
            return Html::checkbox(null, $checked, ['title' => $label, 'value' => $value, 'lay-filter' => $filter]);
        };
        $selected = 'input[name="' . $this->attribute . '"]';

        $js = <<<JS
        layui.use(['form', 'jquery'], function () {
            var form = layui.form, $ = layui.jquery
            form.on('checkbox({$filter})', function(data){
                var val = $('{$selected}').val()
                if (val == '') {
                    arr = []
                } else {
                    arr = val.split(',')
                }
                if (data.elem.checked) {
                    arr.push(data.value)
                } else {
                    arr.forEach(function(item, key) {
                      if (item == data.value) {
                          arr.splice(key, 1)
                      }
                    })
                }
                $('{$selected}').val(arr.join(','))
            });        
        }) 
JS;
        $this->getView()->registerJs($js, View::POS_END);


        return Html::checkboxList($this->attribute, explode(',', $value), $this->items, $options);
    }
}